<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="fetchCode">
        <el-input
          v-model="queryParams.fetchCode"
          placeholder="请输入提货码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-select v-model="form.orderStatus" multiple placeholder="请选择订单状态">
          <el-option
            v-for="item in orderStsList"
            :key="item.orderStatusID"
            :label="item.orderStatusName"
            :value="item.orderStatusID"
            @keyup.enter.native="handleQuery">
          </el-option>
      </el-select>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="订单ID" align="center" prop="id" /> -->
      <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="订单状态" align="center" prop="dtsorderStatus.orderStatusName" />
      <el-table-column label="订单金额" align="center" prop="orderPrice" />
      <el-table-column label="支付金额" align="center" prop="actualPrice" />
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流单号" align="center" prop="shipSn" />
      <el-table-column label="物流渠道" align="center" prop="shipChannel" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:order:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refund"
            v-if="scope.row.dtsorderStatus && scope.row.dtsorderStatus.orderStatusID === 202"
            @click="handleRefund(scope.row)"
            v-hasPermi="['order:order:refund']"
          >退货</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refund"
            v-if="scope.row.dtsorderStatus && scope.row.dtsorderStatus.orderStatusID === 201"
            @click="handleFa(scope.row)"
            v-hasPermi="['order:order:refund']"
          >发货</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog title="订单详情" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单编号" prop="orderSn">
          <span>{{ form.orderSn }}</span>
        </el-form-item>

        <el-form-item label="订单状态" prop="dtsorderStatus">
          <div class="sho-flex">
            <span v-if="form.dtsorderStatus && form.dtsorderStatus != ''">
              {{ form.dtsorderStatus.orderStatusName }}
            </span>
            <span v-if="form.fetchCode != null && form.fetchCode !== ''">
              提货码{{ form.fetchCode }}
            </span>
          </div>
        </el-form-item>

        <el-form-item label="订单用户" prop="userList">
          <span v-if="form.userList && form.userList.length > 0">
            {{ form.userList[0].nickname }}
          </span>
        </el-form-item>
        <el-form-item label="用户留言" prop="message">
          <span>{{ form.message }}</span>
        </el-form-item>

        <el-form-item label="收货信息" prop="consignee">
          <div class="sho-flex">
            <span>(收货人) {{ form.consignee }}</span>
            <span>(手机号) {{ form.mobile }}</span>
            <span>(地址) {{ form.address }}</span>
          </div>
        </el-form-item>

        <!--商品信息-->
        <el-form-item style="position: relative; left:-70px;width: 800px;">
          <el-table :data="form.orderGoodsList" border style="width: 100%;">
            <el-table-column label="商品名称" prop="goodsName" :show-overflow-tooltip="true">
              <template slot-scope="scope" >
                <span>
                  {{ scope.row.goodsName }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="商品编号" prop="goodsSn"></el-table-column>
            <el-table-column label="货品规格" prop="specifications">
              <template slot-scope="scope">
                <!-- 处理数组字符串格式的规格数据 -->
                {{ Array.isArray(scope.row.specifications) ? scope.row.specifications.join(' ') : scope.row.specifications.replace(/[\[\]",]/g, '') }}
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="price"></el-table-column>
            <el-table-column label="数量" prop="number"></el-table-column>
            <el-table-column label="状态" prop="form.orderStatus">
                <template slot-scope="scope">
                  {{ scope.row.orderStatus === 202 ? '退货' : scope.row.orderStatus === 203 ? '退货' : '正常' }}
                </template>
            </el-table-column>
            <el-table-column label="图片">
              <template slot-scope="scope">
                <img :src="scope.row.picUrl" alt="" style="width: 50px; height: 50px;">
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="费用信息" prop="orderPrice">
          <div class="sho-flex">
            <span>(实际费用) {{ form.actualPrice }}元=</span>
            <span>(商品总价) {{ form.goodsPrice }}+</span>
            <span>(快递费用) {{ form.freightPrice }}元-</span>
            <span>(优惠减免) {{ form.couponPrice }}元-</span>
            <span>(积分减免) {{ form.integralPrice }}元</span>
          </div>
        </el-form-item>

        <el-form-item label="支付信息" prop="orderPrice">
          <div class="sho-flex">
            <span>(支付渠道) {{ form.payId }}</span>
            <span>(支付时间) {{ form.payTime }}</span>
          </div>
        </el-form-item>

        <el-form-item label="快递信息" prop="shipChannel">
          <div class="sho-flex">
            <span>(快递公司) {{ form.shipChannel }}</span>
            <span>(快递单号) {{ form.shipSn }}</span>
            <span>(发货时间) {{ form.shipTime }}</span>
          </div>
        </el-form-item>

        <el-form-item label="收货信息" prop="confirmTime">
          <span>(确认收货时间) {{ form.confirmTime }}</span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button>打 印</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--退款框-->
    <el-dialog title="退款记录" :visible.sync="refundDialogVisible" width="70%">
          <el-table :data="refundData" v-loading="refundLoading">
            <el-table-column label="订单编号" prop="orderSn" align="center" />
            <el-table-column label="退款金额" prop="refundAmount" align="center" />
            <el-table-column label="退款状态" align="center">
              <template slot-scope="scope">
                {{ formatRefundStatus(scope.row.status) }}
              </template>
            </el-table-column>
            <el-table-column label="退款原因" prop="refundReason" align="center" />
            <el-table-column label="申请时间" prop="addTime" align="center" width="180">
              <template slot-scope="scope">
                {{ parseTime(scope.row.addTime) }}
              </template>
            </el-table-column>
            <el-table-column label="处理时间" prop="approveTime" align="center" width="180">
              <template slot-scope="scope">
                {{ scope.row.approveTime ? parseTime(scope.row.approveTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.status === 0"
                  type="success"
                  size="mini"
                  @click="handleApproveRefund(scope.row, 1)"
                >同意退款</el-button>
                <el-button
                  v-if="scope.row.status === 0"
                  type="danger"
                  size="mini"
                  @click="handleApproveRefund(scope.row, 2)"
                >拒绝退款</el-button>
                <el-button
                  v-if="scope.row.status === 1"
                  type="primary"
                  size="mini"
                  @click="handleCompleteRefund(scope.row)"
                >完成退款</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer">
            <el-button @click="refundDialogVisible = false">关 闭</el-button>
          </div>
        </el-dialog>

  </div>
</template>

<style scoped>
  .sho-flex{
     display: flex;
    gap: 15px;
  }
</style>

<script>
import { listOrder, getOrder, delOrder, addOrder,
updateOrder,listStatus,selectRefund,approveRefund,completeRefund } from "@/api/emporium/order";

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      //订单状态列表数据
      orderStsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        userId: null,
        orderStatus: null,
        fetchCode:null,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
      },
      refundDialogVisible: false, // 退款对话框显示状态
      refundData: [],            // 退款记录数据
      refundLoading: false,      // 退款记录加载状态
      currentOrderSn: null,      // 当前操作的订单编号
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      listStatus().then(response => {
        this.orderStsList = response;
        console.log(this.orderStsList)
      });
    },
    // 处理退货按钮点击
    handleRefund(row) {
      this.currentOrderSn = row.orderSn;
      this.refundLoading = true;
      this.refundDialogVisible = true;

      const orderSn = row.orderSn;
      // 调用API查询退款记录
      selectRefund(orderSn).then(response => {
        this.refundData = response.data ? [response.data] : []; // 兼容单条数据
        console.log("biaoshuju"+refundData);
        console.log(JSON.stringify(refundData, null, 2));
        console.log(JSON.stringify(response, null, 2));
        this.refundLoading = false;
      }).catch(() => {
        this.refundLoading = false;
        // this.$modal.msgError("查询退款记录失败");
      });
    },
    //发货
    handleFa(row) {
      const id = row.id;
      const orderStatus = 301;
      this.$confirm(`确定发货吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateOrder({
         id,
         orderStatus
        }).then(response => {
          this.$modal.msgSuccess(`发货成功`);
          this.getList(); // 刷新
        }).catch(() => {
          this.$modal.msgError(`发货失败`);
        });
      });
    },

    // 格式化退款状态
    formatRefundStatus(status) {
      const statusMap = {
        0: '申请中',
        1: '已通过',
        2: '已拒绝',
        3: '已完成'
      };
      return statusMap[status] || '未知状态';
    },

    // 处理退款审批
    handleApproveRefund(row, status) {
      const action = status === 1 ? "同意" : "拒绝";
      this.$confirm(`确定${action}该退款申请吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        approveRefund({
          id: row.id,
          status: status,
          approveMsg: `${action}退款申请`
        }).then(response => {
          this.$modal.msgSuccess(`${action}成功`);
          this.handleRefund({ orderSn: this.currentOrderSn }); // 刷新退款记录
        }).catch(() => {
          this.$modal.msgError(`${action}失败`);
        });
      });
    },

    // 完成退款
    handleCompleteRefund(row) {
      this.$confirm("确定已完成退款操作吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        completeRefund({
          id: row.id,
          refundTime: new Date(),
          orderId : row.orderId
        }).then(response => {
          this.$modal.msgSuccess("退款完成");
          this.handleRefund({ orderSn: this.currentOrderSn }); // 刷新退款记录
        }).catch(() => {
          this.$modal.msgError("操作失败");
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderSn: null,
        userId: null,
        orderStatus: null,
        orderPrice: null,
        actualPrice: null,
        payTime: null,
        shipSn: null,
        shipChannel: null,
        consignee: null,
        mobile: null,
        address: null,
        message: null,
        goodsPrice: null,
        freightPrice: null,
        couponPrice: null,
        integralPrice: null,
        grouponPrice: null,
        payId: null,
        shipTime: null,
        confirmTime: null,
        comments: null,
        endTime: null,
        addTime: null,
        updateTime: null,
        deleted: null,
        settlementMoney: null,
        settlementStatus: null,
        freightType: null,
        shareUserId: null,
        fetchCode: null,
        createUserId: null,
        giftSendTime: null,
        giftReceiveTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.orderStatus =  this.form.orderStatus.join(",");
      console.log(this.queryParams.orderStatus);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单管理编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
